package com.game.logic.fighting.skill.buff;

import com.coment.game.fight.Attribute;
import com.coment.game.fight.Attrs;
import com.coment.message.BuffInfo;
import com.coment.po.roles.Roles;
import com.game.dao.user.roles.RolesDao;
import com.xs.build.server.websocket.channel.ClientManager;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/// buff事件-处理者
@Slf4j
@Component
public class BuffEventHandler {
    @Resource
    private RolesDao rolesDao;

    /// 触发属性buff
    @Async
    @EventListener(classes = AttrsBuffEvent.class)
    public void assignAttrsBuffToRoles(AttrsBuffEvent event) {
        BuffInfo buffInfo = event.getBuffInfo();

        String rolesId = buffInfo.rolesId;
        Roles roles = rolesDao.findByIdMust(rolesId);
        Attrs updateValue = roles.rolePanel.obtainUpdateAttrs(buffInfo.addValue);

        if (updateValue.hasValue()) {
            roles.rolePanel.fightPanel.clear();
            buffInfo.addValue = updateValue;
            roles.rolePanel.fightPanel.buff.add(buffInfo);

            rolesDao.save(roles);
            StringBuilder logInfo = Attribute.getLogInfo(updateValue);
            log.debug("角色ID: {} buff生效({}) {}", rolesId,buffInfo.getDuration() , logInfo);

            ClientManager.sendMessageToClient(event.getAnchorInfoId(), buffInfo);
        }
    }

    @Getter
    public static class AttrsBuffEvent extends ApplicationEvent {
        private final Integer anchorInfoId;
        private final BuffInfo buffInfo;

        public AttrsBuffEvent(Object source, Integer anchorInfoId, BuffInfo buffInfo) {
            super(source);
            this.buffInfo = buffInfo;
            this.anchorInfoId = anchorInfoId;
        }
    }
}
